package com.uduemc.security.core.component;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.ServletRequestUtils;

import com.uduemc.security.core.SecurityProperties;

@Component
public class DefaultValidateCodeImage implements ValidateCodeImage {
	
	@Autowired
	private SecurityProperties securityProperties;
	
	@Override
	public ImageCodeAndBufferedImage createImageCode(HttpServletRequest request) {
		int width = ServletRequestUtils.getIntParameter(request, "width", securityProperties.getValidate().getWidth());
		int height = ServletRequestUtils.getIntParameter(request, "height", securityProperties.getValidate().getHeight());;
		
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

		Graphics graphics = image.getGraphics();
		Random random = new Random();

		graphics.setColor(getRandColor(150, 250));
		graphics.fillRect(0, 0, width, height);
		graphics.setFont(new Font("Time New Roman", Font.ITALIC, 20));
		graphics.setColor(getRandColor(150, 200));
		for (int i = 0; i < 150; i++) {
			int x = random.nextInt(width - 12);
			int y = random.nextInt(height - 12);
			int xl = random.nextInt(12);
			int yl = random.nextInt(12);
			graphics.drawLine(x, y, x + xl, y + yl);
		}

		String sRand = "";
		for (int i = 0; i < securityProperties.getValidate().getLength(); i++) {
			String rand = String.valueOf(random.nextInt(10));
			sRand = sRand.concat(rand);
			graphics.setColor(getRandColor(20, 130));
			graphics.drawString(rand, 14 * i + 6, random.nextInt(6) + 16);
		}

		graphics.dispose();

		return new ImageCodeAndBufferedImage(new ImageCode(sRand, 60), image);
	}

	/**
	 * 生成随机的条文
	 * 
	 * @return
	 */
	private Color getRandColor(int fc, int bc) {
		Random random = new Random();
		if (fc > 255) {
			fc = 255;
		}
		if (bc > 255) {
			bc = 255;
		}
		if (fc < 1) {
			fc = 0;
		}
		if (bc < 1) {
			bc = 0;
		}
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}

}
